package com.k.kpp.web.controller;

import com.k.kc.util.FileUtils;
import com.k.kpp.web.vo.DownloadUserReq;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kivil
 */
@Controller
public class DownloadController {
    @RequestMapping("/downloadPage")
    public String downloadPage() {
        return "download";
    }

    @RequestMapping("/download")
    public void download(HttpServletRequest req, HttpServletResponse res) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        String filePath = req.getSession().getServletContext().getRealPath("/") + "WEB-INF/upload/" + "2.xls";
        try {
            String fileName = "GoodsReport.xls";
            res.setContentType("application/octet-stream;charset=iso8859-1");
            res.setHeader("Content-disposition", "attachment; filename=" + fileName);
            bis = new BufferedInputStream(new FileInputStream(filePath));
            bos = new BufferedOutputStream(res.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            System.err.print("download err:");
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("/download2")
    public void download2(HttpServletResponse res) {
        String file = "c:/test/Log.rar";
        try (FileInputStream fis = new FileInputStream(file)) {

            String downloadFileName = "LogNew.rar";
            res.setContentType("application/octet-stream;charset=iso8859-1");
            res.setHeader("Content-disposition", "attachment; filename=" + downloadFileName);

            FileUtils.save(fis, res.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/download3")
    public void download3(HttpServletResponse res, DownloadUserReq user) {
        System.out.println(user);
        download2(res);
    }

    @RequestMapping("/downloadCsv")
    public void downloadCsv(HttpServletRequest request, HttpServletResponse response) {
        try {
            RequestContext requestContext = new RequestContext(request);
            String encode = "gbk";
            response.reset();
            response.setContentType("application/x-msdownload;charset=utf-8");
            response.setCharacterEncoding(encode);
            String dlFileName = "CallTypeStatistics";
            response.addHeader("Content-Disposition", "attachment; filename=\"" + dlFileName + ".csv" + "\"");
            List<Map<String, String>> list = new ArrayList<>();//statisticsable.downloadCsv(map.get("beginTime")+"", map.get("endTime")+"");
            Map<String, String> map = new HashMap<>();
            map.put("createTime", "2023-05-17 12:20:30");
            map.put("type", "a");
            map.put("value", "2");
            list.add(map);
            StringBuilder sb = new StringBuilder();
            // title
            sb.append(requestContext.getMessage("HOME_TIME")).append(",")
                    .append(requestContext.getMessage("HOME_CALL_TYPE")).append(",")
                    .append(requestContext.getMessage("STATISTICS_UNIT_COUNT")).append("\r\n");
            // data
            for (Map<String, String> rowMap : list) {
                String time = rowMap.get("createTime").split(" ")[0];
                String type = rowMap.get("type");
                String value = rowMap.get("value");
                if ("1".equals(type)) {
                    type = requestContext.getMessage("ADSEARCH_VIDEO");
                } else if ("2".equals(type)) {
                    type = requestContext.getMessage("ADSEARCH_AUDIO");
                } else {
                    type = requestContext.getMessage("CALL_TYPE_" + (Integer.parseInt(type) - 100));
                }
                sb.append(time).append(",").append(type).append(",").append(value).append("\r\n");
            }
            IOUtils.write(sb.toString(), response.getOutputStream(), encode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
